package com.mall.mina.util;

public class CrcUtils {
    /**
     * 生成 CRC校验码
     * @param data
     * @return
     */
    public static byte[] crc16ab(byte[] data) {
        int crc = 0xffff; // initial value
        int polynomial = 0x1021; // poly value
        for (byte b : data) {
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit)
                    crc ^= polynomial;
            }
        }
        byte hi = (byte) ((crc & 0xFF00) >> 8);  //高位置
        byte lo = (byte) (crc & 0x00FF);         //低位置
        return new byte[]{lo, hi};
    }

    /**
     * 对当前完整通用帧格式（前导码、帧头、操作码、负载、校验）进行校验
     * @param args
     * @return
     */
    public static boolean isCrc16(byte[] args){
        if (args == null || args.length < 7){
            throw new IllegalArgumentException("参数异常");
        }
        byte[] bytes = new byte[args.length - 4];
        for (int i = 0,j = 0; i < args.length; i++) {
            if (i > 1 && i < args.length - 2){
                bytes[j] = args[i];
                ++j;
            }
        }
        byte[] crc = crc16ab(bytes);
        if (args[args.length - 2] == crc[0] && args[args.length - 1] == crc[1]){
            return true;
        }
        return false;
    }
}
